package com.econ.powercloud.ems.observer;

import com.econ.powercloud.common.base.facade.util.JacksonUtil;
import com.econ.powercloud.ems.common.enums.ControlRecordStatusEnum;
import com.econ.powercloud.ems.common.interf.ServiceFeedbackDataObserver;
import com.econ.powercloud.ems.common.pojo.EmsMqttReplyVO;
import com.econ.powercloud.ems.dal.entity.EmsControlRecordDetail;
import com.econ.powercloud.ems.dal.entity.EmsControlRecordLog;
import com.econ.powercloud.ems.service.biz.EmsYkYtIssueService;
import com.econ.powercloud.ems.service.dao.EmsControlRecordDetailDAO;
import com.econ.powercloud.ems.service.dao.EmsControlRecordLogDAO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 设备回复 （群控功能）
 * @author jwc
 * @since 2023/06/02
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ControlDealProcessor implements ServiceFeedbackDataObserver {

    private final Integer SUCCESS_CODE = 200;

    private final EmsControlRecordDetailDAO emsControlRecordDetailDAO;
    private final EmsYkYtIssueService emsYkYtIssueService;
    private final EmsControlRecordLogDAO emsControlRecordLogDAO;

    @Override
    public void doInvoke(EmsMqttReplyVO data) {
        log.info("ControlDealProcessor消息消费，数据：{}", data);
        EmsControlRecordDetail recordDetail = emsControlRecordDetailDAO.selectByMsgId(data.getMsgId());
        if (null == recordDetail) {
            log.info("recordDetail is null");
            return;
        }
        //校验当前步骤是否在进行中状态
        if (!recordDetail.getStatus().equals(ControlRecordStatusEnum.IN_PROGRESS.getCode())) {
            String log = String.format("群控群调->已接收kafka推送数据,且记录不处于进行中,步骤信息：%s", JacksonUtil.toJSONString(recordDetail));
            emsControlRecordLogDAO.save(EmsControlRecordLog.builder().recordId(recordDetail.getRecordId()).content(log).gmtCreate(new Date()).build());
            return;
        }
        if (data.getCode().equals(SUCCESS_CODE)) {
            //下发成功
            recordDetail.setStatus(ControlRecordStatusEnum.SUCCESS.getCode());
        } else {
            //下发失败
            recordDetail.setStatus(ControlRecordStatusEnum.FAIL.getCode());
        }
        recordDetail.setGmtModify(System.currentTimeMillis());
        emsControlRecordDetailDAO.updateById(recordDetail);
        String log = String.format("群控群调->已接收kafka推送数据,某个步骤数据更新为：%s", JacksonUtil.toJSONString(recordDetail));
        emsControlRecordLogDAO.save(EmsControlRecordLog.builder().recordId(recordDetail.getRecordId()).content(log).gmtCreate(new Date()).build());
        //步骤是否执行完成
        emsYkYtIssueService.checkRecordDetailStatus(recordDetail);
    }

}
